<template>
  <div class="login-third-root" v-loading="loading">
    <!-- <div class="txt">请稍后...</div> -->
  </div>
</template>

<script>
import db from "utils/localstorage/main.js";
import store from "@/store/index.js";
import axios from "axios";
import { layout } from "@/settings";
import { getQueryString } from "@/utils/assist.js";
import { Loading } from 'element-ui';

export default {
  name: "login-third",
  components: {},
  data() {
    return {
      loading: false,
      loginForm: {
        a: "",
        b: ""
      }
    }
  },
  methods: {
    login(){
      const that = this;
      const data = window.microApp.getData();
      let path = data.path;
      let sgAccount = data.account;
      let server = path.indexOf('/')==0 ? path.substr(1, path.length-1) : path;
      server = server.indexOf('/')>0 ? server.substr(0, server.indexOf('/')) : server;
      const state = path.indexOf('/')==0 ? path.substr(1,path.length-1) : path;
      console.log(server, sgAccount)
      // 判断是否已经进来过
      const key = 'SESSION__KEY__';
      let sgSessionId = this.sessionStorageTool(key)
      let compareStr = server + "_" + sgAccount
      if (sgAccount != null && sgSessionId != null && sgSessionId == compareStr) {
          this.loading = false;
          this.$router.push("/"+state);
          return;
        }
      // 第一次进来清除上次认证信息
      localStorage.removeItem("ACCESS_TOKEN");
      localStorage.removeItem("REFRESH_TOKEN");
      localStorage.removeItem("EXPIRE_TIME");
      localStorage.removeItem("USER");
      localStorage.removeItem("USER_ROUTER");
      localStorage.removeItem("PERMISSIONS");
      sessionStorage.removeItem(key);

      this.$login("auth/oauth/token", {
          ...that.loginForm
        })
          .then((r) => {
            const data = r;
            this.saveLoginData(data);
            this.getUserDetailInfo(state);
          })
          .catch((error) => {
            this.$message({
              message: "授权异常，请重新进入",
              type: "error",
            });
          });
    },
    sglogin() {
      const data = window.microApp.getData();
      let path = data.path;
      let sgAccount = data.account;
      let server = path.indexOf('/')==0 ? path.substr(1, path.length-1) : path;
      server = server.indexOf('/')>0 ? server.substr(0, server.indexOf('/')) : server;
      const state = path.indexOf('/')==0 ? path.substr(1,path.length-1) : path;
      console.log(server, sgAccount)
      // 判断是否已经进来过
      const key = 'SESSION__KEY__';
      let sgSessionId = this.sessionStorageTool(key)
      let compareStr = server + "_" + sgAccount
      if (sgAccount != null && sgSessionId != null && sgSessionId == compareStr) {
          this.loading = false;
          this.$router.push("/"+state);
          return;
        }
      // 第一次进来清除上次认证信息
      localStorage.removeItem("ACCESS_TOKEN");
      localStorage.removeItem("REFRESH_TOKEN");
      localStorage.removeItem("EXPIRE_TIME");
      localStorage.removeItem("USER");
      localStorage.removeItem("USER_ROUTER");
      localStorage.removeItem("PERMISSIONS");
      sessionStorage.removeItem(key);
      // 授权
      const baseUrl = process.env.VUE_APP_BASE_API;
      axios({
        method: "post",
        url: baseUrl + `auth/uaa/convertToken?state=` + server,
        headers: {
          "Content-Type": "application/json"
        },
      }).then((res) => {
        console.log(res)
        if (res.data.code == 200) {
          this.saveLoginData(res.data.data)
          this.getUserDetailInfo(state)
          if (sgAccount != null && sgAccount != '') {
            sessionStorage.setItem(key, compareStr);
          }
          this.loading = false;
        } else {
          this.$message({
            message: "授权异常，请重新进入",
            type: "error",
          });
          this.loading = false;
        }
      });
    },
    saveLoginData(data) {
      console.log('save',data)
      this.$store.commit("account/setAccessToken", data.access_token);
      this.$store.commit("account/setRefreshToken", data.refresh_token);
      this.$store.commit("account/setUser", 'user');
      
      const current = new Date();
      const expireTime = current.setTime(
        current.getTime() + 1000 * data.expires_in
      );
      this.$store.commit("account/setExpireTime", expireTime);

      this.$store.commit("setting/setHeaderHidden", true);
      // this.$router.push("/");
    },
    getUserDetailInfo(state) {
      this.$get("auth/user")
        .then((r) => {
          this.$store.commit("account/setUser", r.principal);
          // 获取数据字典
          this.$commonJs.getAllDataDictionary();
          this.$router.push("/"+state);
          this.loading = false;
        })
        .catch((error) => {
          this.$message({
            message: "授权异常，请重新进入",
            type: "error",
          });
          this.loading = false;
          console.error(error);
        });
    },
    sessionStorageTool(cname){
      for (let index = 0; index < sessionStorage.length; index++) {
        let name = sessionStorage.key(index);
        if (name.indexOf(cname) >= 0) {
          return sessionStorage.getItem(name);
        }
      }
      return '';
    }
  },
  mounted() {
    // db.clear();
    // 测试环境
    // this.login();
    // 生产环境
    localStorage.removeItem("MENU_HIDDEN");
    this.loading = true;
    this.sglogin();
  },
};
</script>

<style lang="scss" scoped>
.login-third-root {
  height: 100%;
  .txt{
    margin-top: 20vh;
    text-align: center;
    font-size: 24px;
  }
}
::v-deep .el-loading-spinner{
  position: fixed;
}
</style>

